package com.hammera.common.permission

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import java.util.*



class PermissionManagerCompat {
    private var requestCode: Int = 0
    private var callback: IPermissionCallBack? = null
    private var mActivity: Activity? = null
    private var mFragment: Fragment? = null
    private var permissions: Array<String>? = null

    private constructor(activity: Activity) {
        this.mActivity = activity
    }

    private constructor(fragment: Fragment) {
        this.mActivity = fragment.activity
        this.mFragment = fragment
    }

    private fun shouldShowRationalePermissions(vararg permissions: String): Boolean {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return false
        }
        for (permission in permissions) {
            val rationale = mActivity?.shouldShowRequestPermissionRationale(permission)
            if (rationale == true) {
                return true
            }
        }
        return false
    }

    /**
     * 用户拒绝授权，并勾选了下次不再提醒
     *
     * @param deniedPermissions
     * @return
     */
    private fun hasAlwaysDeniedPermission(vararg deniedPermissions: String): Boolean {
        return !shouldShowRationalePermissions(*deniedPermissions)
    }

    /**
     * 权限授权成功
     */
    private fun succeed() {
        callback?.success(mActivity!!, requestCode)
    }

    /**
     * 用户拒绝了某个或者某些权限
     *
     * @param deniedList
     */
    private fun failed(vararg deniedList: String) {
        if (hasAlwaysDeniedPermission(*deniedList)) {
            callback?.alwaysDenied(mActivity!!, requestCode, *deniedList)
        } else {
            callback?.fail(mActivity!!, requestCode, *deniedList)
        }
    }


    /**
     * 请求码
     *
     * @param requestCode
     * @return
     */
    fun requestCode(requestCode: Int): PermissionManagerCompat {
        this.requestCode = requestCode
        return this
    }

    /**
     * 要请求的权限
     *
     * @param permissions
     * @return
     */
    fun permissions(vararg permissions: String): PermissionManagerCompat {
        this.permissions = arrayOf(*permissions)
        return this
    }

    /**
     * @param callBack
     * @return
     */
    fun callback(callBack: IPermissionCallBack): PermissionManagerCompat {
        this.callback = callBack
        return this
    }

    /**
     * 开始申请权限
     */
    fun start() {
        if (!isSatisfactionRequestPermission) {
            succeed()
        } else if (permissions == null) {
            failed()
        } else {
            request(*permissions!!)
        }
    }

    private fun request(vararg permissions: String) {
        val mDeniedPermissions = getDeniedPermissions(mActivity, *permissions)

        if (mDeniedPermissions.isNotEmpty()) {//有权限没有授权
            mFragment?.requestPermissions(mDeniedPermissions, requestCode)
                    ?: ActivityCompat.requestPermissions(mActivity!!, mDeniedPermissions,
                            requestCode)
        } else { // 全部都已经授权过了
            succeed()
        }
    }


    /**
     * 如果用户勾选了不再提示，打开APP设置，引导用户手动开启
     */
    fun showSetting() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", mActivity?.packageName, null)
        intent.data = uri
        mActivity!!.startActivityForResult(intent, requestCode)
    }


    /**
     * 授权的回调
     *
     * @param permissions
     * @param grantResults
     */
    fun onRequestPermissionsResult(vararg permissions: String, grantResults: IntArray) {
        val deniedList = ArrayList<String>()
        for (i in permissions.indices) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                deniedList.add(permissions[i])
            }
        }
        if (deniedList.isEmpty()) {
            succeed()
        } else {
            failed(*deniedList.toTypedArray())
        }
    }

    /**
     * 显示授权对话框
     *
     * @param activity //     * @param quitAppOnCancel 点击取消时，是否要退出app
     */
    fun showRequestPermissionTipsDialog(activity: Activity, msg: String) {
        val dialog = AlertDialog.Builder(activity)
                .setTitle("权限申请")
                .setMessage(msg/*"软件需要使用无法运行应用程序哦，如果取消则程序无法正常运行"*/)
                .setPositiveButton("去设置") { _, _ ->
                    showSetting()
                    activity.finish()
                }
                .setNegativeButton("取消") { _, _ ->
                    activity.finish()
                }
                .setOnCancelListener {
                    activity.finish()
                }.create()
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
    }

    companion object {

        //    public static PermissionManagerCompat getInstance(Fragment fragment) {
        //        if (fragment == null || !fragment.isAdded() || fragment.getActivity() == null) {
        //            throw new RuntimeException("fragment not be null");
        //        }
        //        return new PermissionManagerCompat(fragment);
        //    }

        fun newInstance(fragment: Fragment?): PermissionManagerCompat {
            if (fragment == null || !fragment.isAdded || fragment.activity == null) {
                throw RuntimeException("fragment not be null")
            }
            return PermissionManagerCompat(fragment)
        }

        fun newInstance(activity: Activity?): PermissionManagerCompat {
            if (activity == null) {
                throw RuntimeException("activity not be null")
            }
            return PermissionManagerCompat(activity)
        }

        /**
         * 是否满足版本
         *
         * @return
         */
        private val isSatisfactionRequestPermission: Boolean
            get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M

        /**
         * 是否需要申请权限
         *
         * @param context
         * @param permissions
         * @return
         */
        fun isNeedRequestPermission(context: Context?, vararg permissions: String): Boolean {
            return !(context == null || !isSatisfactionRequestPermission ||
                    getDeniedPermissions(context, *permissions).isEmpty())
        }

        /**
         * 获取未授权列表
         *
         * @return
         */
        private fun getDeniedPermissions(context: Context?, vararg permissions: String): Array<String> {
            val deniedList = ArrayList<String>(1)
            for (permission in permissions) {
                if (ContextCompat.checkSelfPermission(context!!, permission) != PackageManager
                                .PERMISSION_GRANTED) {

                    deniedList.add(permission)
                }
            }
            return deniedList.toTypedArray()
        }
    }
}
